package com.yusi.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yusi.entity.Airplane;
import com.yusi.entity.FlightMana;
import com.yusi.entity.dto.GetCity;
import com.yusi.entity.dto.RespBean;
import com.yusi.entity.dto.RespPageBean;
import com.yusi.mapper.AirplaneMapper;
import com.yusi.mapper.FlightManaMapper;
import com.yusi.service.IFlightManaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yusi
 * @since 2022-01-06
 */
@Service
public class FlightManaServiceImpl extends ServiceImpl<FlightManaMapper, FlightMana> implements IFlightManaService {
    @Autowired
    private FlightManaMapper flightManaMapper;
    @Autowired
    private AirplaneMapper airplaneMapper;

    @Override
    @Transactional
    public RespBean saveAirPort(FlightMana flightMana) {
        int eco = flightMana.getEconomy();
        int bus = flightMana.getBusiness();
        int fir = flightMana.getFirstClass();
        Airplane airplane = airplaneMapper.selectById(flightMana.getAirId());
        int exceed = (int) (airplane.getMaxCarry() - (eco + 1.5 * bus + 2 * fir));
        if (exceed>= 0 && exceed<1) {
            if (flightManaMapper.insert(flightMana)==1){
                return RespBean.success("添加成功！");
            }
            return RespBean.success("添加失败！");
        } else if (exceed >= 1) {
            return RespBean.success("有多余空位，合理安排。", exceed);
        } else {
            return RespBean.error("添加失败", exceed);
        }
    }

    @Override
    public RespPageBean getAirPort(Integer currentpage, Integer size,String input, FlightMana flightMana, LocalDate[] beginDateScope) {
        //        分页查询的原理
//        1.先完成分页的配置
        Page<FlightMana> page = new Page<>(currentpage, size);
//        2.编写正常的sql语句但是不带分页语句
        IPage<FlightMana> employeeByPage = flightManaMapper.getAirPort(page,input,flightMana,beginDateScope);
//        3.在进行分页查询的时候，会拦截sql语句，加上分页的语句，完成分页查询。
        RespPageBean respPageBean = new RespPageBean(employeeByPage.getTotal(), employeeByPage.getRecords());
        return respPageBean;
    }

    @Override
    public List<GetCity> getairbydis(Double dis) {
        List<FlightMana> list=flightManaMapper.getairbydis(dis);
        ArrayList<GetCity> relist = new ArrayList<>();
        for (FlightMana f:list) {
            if (dis<f.getAirplane().getMaxDis()) {
                relist.add(new GetCity().setValue(f.getId()).setLabel(f.getAirName()+"~"+f.getAirplane().getAirplaneType()));
            }else{
                continue;
            }
        }
        return relist;
    }


}
